package com.nepu.gmall.realtime.util;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidPooledConnection;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.nepu.gmall.realtime.common.GmallConfig;
import redis.clients.jedis.Jedis;

import java.lang.reflect.InvocationTargetException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

import static com.nepu.gmall.realtime.util.JdbcUtil.queryList;

/**
 * @author chenshuaijun
 * @create 2023-03-03 20:11
 */
public class DimUtil {

    public static JSONObject getDimInfo(Connection connection, String tableName, String key) throws InvocationTargetException, SQLException, InstantiationException, IllegalAccessException {

        // TODO 为了加快查询的速度，我将在这里先查询缓存
        Jedis jedis = JedisUtil.getJedis();
        String redisKey = "DIM:" + tableName + ":" + key;
        String info = jedis.get(redisKey);
        if (info != null){
            System.out.println("我来到就这里");
            // 更新key的过期时间
            jedis.expire(redisKey,24*60*60);
            // 归还redis连接
            jedis.close();
            // 返回数据
            return JSON.parseObject(info);
        }

        String sql = "select * from "+GmallConfig.HBASE_SCHEMA+"."+tableName+" where id = '"+key+"'";

        List<JSONObject> jsonObjects = queryList(connection, sql, JSONObject.class, false);

        // TODO 如果走到这一步的时候，表示redis中没有缓存数据，所以这里需要加缓存
        JSONObject jsonObject = jsonObjects.get(0);
        // 将数据存储到redis
        jedis.set(redisKey,jsonObject.toJSONString());
        // 设置key的过期时间
        jedis.expire(redisKey,24*60*60);
        // 归还连接
        jedis.close();
        // 因为做维度关联的时候只能查出来一天数据，所以这里直接取出这一条数据
        return jsonObject;

    }

    /**
     * 如果检测到当前的操作是更新操作，那么直接删除redis中对于key的数据
     * @param tableName
     * @param key
     */
    public static void deleteRedisData(String tableName, String key){
        String redisKey = "DIM:" + tableName + ":" + key;
        Jedis jedis = JedisUtil.getJedis();
        jedis.del(redisKey);
        jedis.close();
    }

    public static void main(String[] args) throws Exception {
        DruidDataSource dataSource = DruidDSUtil.createDataSource();
        DruidPooledConnection connection = dataSource.getConnection();
        long start = System.currentTimeMillis();
        JSONObject dimInfo = getDimInfo(connection  , "DIM_BASE_TRADEMARK", "13");
        long end = System.currentTimeMillis();
        System.out.println(end - start);
        System.out.println(dimInfo);
        connection.close();

    }
}
